package cc.shacocloud.mirage.loader;

import java.lang.reflect.Method;

/**
 * Mirage  启动器的顶层类
 *
 * @author 思追(shaco)
 */
public interface Launcher {
    
    String START_CLASS_ATTRIBUTE = "Mirage-Start-Class";
    
    String CLASSES_ATTRIBUTE = "Mirage-Classes";
    
    String LIB_INDEX_ATTRIBUTE = "Mirage-Lib-Index";
    
    /**
     * 解压目录的参数键，可以使用 {@code System.getProperty(MIRAGE_UNPACK_DIRECTORY_PROPERTY_KEY)} 获取
     */
    String MIRAGE_UNPACK_DIRECTORY_PROPERTY_KEY = "mirage.unpack-directory";
    
    /**
     * 启动方法
     *
     * @param args 启动参数
     */
    default void run(String[] args) throws Exception {
        // 创建类加载器
        ClassLoader classLoader = createClassLoader();
        Thread.currentThread().setContextClassLoader(classLoader);
        
        // 执行主类
        Class<?> mainClass = classLoader.loadClass(getMainClassName());
        Method mainMethod = mainClass.getDeclaredMethod("main", String[].class);
        mainMethod.setAccessible(true);
        mainMethod.invoke(null, new Object[]{args});
    }
    
    /**
     * 创建类加载器
     */
    ClassLoader createClassLoader() throws Exception;
    
    /**
     * 获取运行的主类名称
     */
    String getMainClassName() throws Exception;
}
